package com.huayal.mall.search.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huayal.common.constant.ESConstant;
import com.huayal.common.vo.es.SkuESModel;
import com.huayal.mall.search.config.EsConfig;
import com.huayal.mall.search.service.SkuAddService;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.Level;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Log4j2
@Service
public class SkuAddServiceImpl implements SkuAddService {


    @Autowired
    private RestHighLevelClient restHighLevelClient;



    @Override
    public Boolean saveSkuESModels(List<SkuESModel> skuESModels)  {

        BulkResponse bulkResponse =null;
        try {
            BulkRequest bulkRequest = new BulkRequest();

            for (SkuESModel sku:skuESModels){
                IndexRequest indexRequest = new IndexRequest(ESConstant.ProductEnum.ES_PRODUCT_INDEX.getName());
                indexRequest.id(sku.getSkuId().toString());

                ObjectMapper objectMapper = new ObjectMapper();
                String json = objectMapper.writeValueAsString(sku);

                IndexRequest source = indexRequest.source(json, XContentType.JSON);
                bulkRequest.add(source);
            }

            bulkResponse = restHighLevelClient.bulk(bulkRequest, EsConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("----->商品上架失败，出现IOException异常！");
            return false;
        }

        boolean b = bulkResponse.hasFailures();
        if (b){
            BulkItemResponse[] items = bulkResponse.getItems();
            for (BulkItemResponse response:items){
                log.log(Level.INFO,"sku反馈信息："+response.getFailure()+","+response.getFailureMessage());
            }
            return false;
        }

        return true;
    }
}
